package phone.qyg.com.qyg.activity.baidu;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.app.baidu.location.MyOrientationListener;
import com.app.base.tool.BaseActivity;
import com.app.config.ApplicationConfig;
import com.app.utils.PromptManager;
import com.app.utils.TransformController;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.mapapi.overlayutil.PoiOverlay;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.MapItem;


/**
 * 作者：lblbh on 2017/6/14 10:55
 * 邮箱：lanbuhan@163.com
 * 功能：周边搜索
 */
@ContentView(R.layout.periphery)
public class PeripheryActivity extends BaseActivity implements OnGetPoiSearchResultListener {

    String PARCELABLE_FITNESS = "PARCELABLE_FITNESS";

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.bmapView)
    MapView bmapView;

    String key;

    MapItem mapItem;

    SuggestionResult.SuggestionInfo suggestionInfo;

    BaiduMap mBaiduMap;

    // 定位相关
    private LocationClient mLocationClient;
    private MyLocationListener mLocationListener;
    private boolean isFirstIn = true;
    private double mLatitude;
    private double mLongtitude;
    // 自定义定位图标
    private BitmapDescriptor mIconLocation;
    private MyOrientationListener myOrientationListener;
    private float mCurrentX;
    private MyLocationConfiguration.LocationMode mLocationMode;

    // 覆盖物相关
    private BitmapDescriptor mMarker;


    PoiSearch mPoiSearch = null;

    int radius = 2000; //搜索范围

    boolean isLocalVis; //显示下面地址

    @Override
    public void initSucessView() {
        Intent intent = getIntent();
        if(intent != null){
            Bundle bundle = intent.getBundleExtra(TransformController.ChangeKEY.INTENT_KEY);
            if(bundle != null){

                key = bundle.getString(ApplicationConfig.APP_KEY_TRANS,"");

                suggestionInfo = bundle.getParcelable(ApplicationConfig.APP_INFO_TRANS);

                mapItem = bundle.getParcelable(ApplicationConfig.APP_INFO_TWO_TRANS);
            }
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initBMapView();
        initLocation();

        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        LatLng latLng = new LatLng(Double.valueOf(mapItem.latitude),Double.valueOf(mapItem.longitude));

        addOverlays(mapItem);

        if(isRequestStr(key)){
            //多个点
            PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption().keyword(key)
                    .sortType(PoiSortType.distance_from_near_to_far).location(latLng)
                    .radius(radius).pageNum(0).pageCapacity(20);
            mPoiSearch.searchNearby(nearbySearchOption);
        }else{
            //一个点
            PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption().keyword(suggestionInfo.key)
                    .sortType(PoiSortType.distance_from_near_to_far).location(latLng)
                    .radius(radius).pageNum(0).pageCapacity(20);
            mPoiSearch.searchNearby(nearbySearchOption);
        }
    }


    /**
     * 添加覆盖物
     *
     */
    private void addOverlays(MapItem mapItem) {
        mBaiduMap.clear();
        // 经纬度
        LatLng latLng = new LatLng(Float.valueOf(mapItem.latitude), Float.valueOf(mapItem.longitude));
        // 图标
        OverlayOptions options = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.find_map_icon))
                .zIndex(5);
        Marker marker = (Marker) mBaiduMap.addOverlay(options);
        Bundle arg0 = new Bundle();
        arg0.putParcelable(PARCELABLE_FITNESS, mapItem);
        marker.setExtraInfo(arg0);

        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
//        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);

        mBaiduMap.setMapStatus(msu);

        //画圆 去掉
//        showNearbyArea(latLng, radius);

    }

    private void initBMapView() {
        mBaiduMap = bmapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(20.0f);
        mBaiduMap.setMapStatus(msu);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        bmapView.onResume();
    }

    @Override
    public void onStart()
    {
        super.onStart();
        // 开启定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted())
            mLocationClient.start();
        // 开启方向传感器
        myOrientationListener.start();
    }

    public void onPause()
    {
        super.onPause();
        // 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        bmapView.onPause();
    }


    private void initLocation(){

        mLocationMode = MyLocationConfiguration.LocationMode.NORMAL;
        mLocationClient = new LocationClient(this);
        mLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mLocationListener);

        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
        // 初始化图标
//        mIconLocation = BitmapDescriptorFactory
//                .fromResource(R.drawable.navi_map_gps_locked);
        //"
        mIconLocation = BitmapDescriptorFactory.fromPath(ApplicationConfig.NET_DSN_PATH + "/relfile/images/mapIco/venue_ico.png");
        myOrientationListener = new MyOrientationListener(this);

        myOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener()
                {
                    @Override
                    public void onOrientationChanged(float x)
                    {
                        mCurrentX = x;
                    }
                });

    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(final BDLocation location) {

            MyLocationData data = new MyLocationData.Builder()//
                    .direction(mCurrentX)//
                    .accuracy(location.getRadius())//
                    .latitude(location.getLatitude())//
                    .longitude(location.getLongitude())//
                    .build();
            mBaiduMap.setMyLocationData(data);
            // 设置自定义图标
            MyLocationConfiguration config = new MyLocationConfiguration(
                    mLocationMode, true, mIconLocation);
            mBaiduMap.setMyLocationConfigeration(config);

            // 更新经纬度
            mLatitude = location.getLatitude();
            mLongtitude = location.getLongitude();

            if (isFirstIn){

                //当前位置弹出
                LatLng latLng = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
//                mBaiduMap.animateMapStatus(msu);
                isFirstIn = false;

            }

        }

        public void onConnectHotSpotMessage(String s, int i) {

        }

    }

    @Override
    public void onGetPoiResult(PoiResult result) {//PoiResult result
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            PromptManager.showToast(R.string.find_map_empty);
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
//            mBaiduMap.clear();
            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(result);
            overlay.addToMap();
            overlay.zoomToSpan();

            return;
        }
    }



    @Override
    public void onGetPoiDetailResult(PoiDetailResult result) {
        //点击详情
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
            PromptManager.showToast(R.string.find_map_empty);
        } else {

            final View view = View.inflate(getApplicationContext(),R.layout.baidu_popu_address,null);
            TextView nameView = (TextView)view.findViewById(R.id.name);
            TextView addressView = (TextView)view.findViewById(R.id.address);
            nameView.setText(result.getName());
            addressView.setText(result.getAddress());
            InfoWindow.OnInfoWindowClickListener listener = new InfoWindow.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick() {
                    mBaiduMap.hideInfoWindow();
                }
            };
            LatLng ll = result.getLocation();
            InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), ll, -47, listener);
                mBaiduMap.showInfoWindow(mInfoWindow);
//            view.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//
//                }
//            });
        }
    }


    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {}


    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                    .poiUid(poi.uid));
            return true;
        }
    }

    @Event(value = {R.id.back})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
        }
    }

    @Override
    public void initViewHandler() {}
}
